<template>
  <div class="preview-editor-container">
    <!-- 顶部工具栏 -->
    <div class="toolbar">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/static-site/static-site-category/', query: { site_id: siteId, site_name: siteName } }">
          {{ siteName }} - 分类管理
        </el-breadcrumb-item>
        <el-breadcrumb-item>{{ categoryName }} - 预览修改</el-breadcrumb-item>
      </el-breadcrumb>

      <div class="toolbar-actions">
        <el-button size="small" @click="resetCode">重置代码</el-button>
        <el-button size="small" type="primary" :loading="saving" @click="saveCode">保存修改</el-button>
        <el-button size="small" @click="closeEditor">关闭</el-button>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 左侧预览区域 -->
      <div class="preview-panel">
        <div class="panel-header">
          <h4>预览</h4>
          <div class="preview-controls">
            <el-button-group size="mini">
              <el-button :type="viewportMode === 'desktop' ? 'primary' : ''" @click="setViewport('desktop')">
                <i class="el-icon-monitor" /> 桌面
              </el-button>
              <el-button :type="viewportMode === 'tablet' ? 'primary' : ''" @click="setViewport('tablet')">
                <i class="el-icon-mobile" /> 平板
              </el-button>
              <el-button :type="viewportMode === 'mobile' ? 'primary' : ''" @click="setViewport('mobile')">
                <i class="el-icon-mobile-phone" /> 手机
              </el-button>
            </el-button-group>
            <el-button size="mini" @click="refreshPreview">
              <i class="el-icon-refresh" /> 刷新
            </el-button>
            <el-button
              size="mini"
              :type="inspectMode ? 'primary' : ''"
              :title="inspectMode ? '退出检查模式 (Esc)' : '开启元素检查模式 (Ctrl+Shift+I)'"
              @click="toggleInspectMode"
            >
              <i class="el-icon-aim" /> {{ inspectMode ? '退出检查' : '检查元素' }}
            </el-button>
          </div>
        </div>
        <div class="preview-content" :class="viewportClass">
          <iframe
            ref="previewFrame"
            :srcdoc="previewHtml"
            width="100%"
            height="100%"
            frameborder="0"
            sandbox="allow-scripts allow-same-origin"
            @load="onPreviewLoad"
          />

          <!-- 元素检查模式提示 -->
          <div v-if="inspectMode" class="inspect-mode-tip">
            <div class="tip-content">
              <i class="el-icon-aim" />
              <span>元素检查模式：单击定位代码，双击快速编辑</span>
              <el-button size="mini" type="text" @click="toggleInspectMode">
                <i class="el-icon-close" />
              </el-button>
            </div>
          </div>
        </div>
      </div>

      <!-- 右侧代码编辑区域 -->
      <div class="editor-panel">
        <div class="panel-header">
          <h4>HTML代码编辑器</h4>
          <div class="editor-controls">
            <span v-if="selectedText" class="selection-info">
              已选择: {{ selectedText.length }} 个字符
            </span>
            <span v-else class="selection-hint">
              <i class="el-icon-info" />
              可选择代码片段进行AI精准修改
            </span>
            <el-button size="mini" @click="formatCode">
              <i class="el-icon-magic-stick" /> 格式化
            </el-button>
            <el-button size="mini" @click="toggleSearch">
              <i class="el-icon-search" /> 搜索
            </el-button>
          </div>
        </div>

        <!-- 搜索框 -->
        <div v-if="showSearch" class="search-container">
          <div class="search-input-group">
            <el-input
              ref="searchInput"
              v-model="searchQuery"
              placeholder="搜索代码... (支持正则表达式)"
              class="search-input"
              clearable
              @keyup.enter="searchNext"
              @keyup.esc="closeSearch"
              @keydown.shift.enter="searchPrevious"
              @input="performSearch"
              @focus="handleSearchFocus"
              @blur="handleSearchBlur"
            >
              <template slot="prepend">
                <i class="el-icon-search" />
              </template>
              <template slot="append">
                <el-tooltip content="区分大小写" placement="top">
                  <el-button
                    size="mini"
                    :type="searchOptions.caseSensitive ? 'primary' : ''"
                    class="search-option-btn"
                    @click="toggleCaseSensitive"
                  >
                    Aa
                  </el-button>
                </el-tooltip>
                <el-tooltip content="正则表达式" placement="top">
                  <el-button
                    size="mini"
                    :type="searchOptions.useRegex ? 'primary' : ''"
                    class="search-option-btn"
                    @click="toggleRegex"
                  >
                    .*
                  </el-button>
                </el-tooltip>
              </template>
            </el-input>
            <div class="search-buttons">
              <el-button-group size="mini">
                <el-button :disabled="searchMatches.length === 0" title="上一个 (Shift+Enter)" @click="searchPrevious">
                  <i class="el-icon-arrow-up" />
                </el-button>
                <el-button :disabled="searchMatches.length === 0" title="下一个 (Enter)" @click="searchNext">
                  <i class="el-icon-arrow-down" />
                </el-button>
              </el-button-group>
              <span class="search-count">{{ getSearchStatusText() }}</span>
              <el-button size="mini" type="text" title="关闭 (Esc)" @click="closeSearch">
                <i class="el-icon-close" />
              </el-button>
            </div>
          </div>

          <!-- 搜索历史下拉建议 -->
          <div v-if="showSuggestions && searchHistory.length > 0" class="search-suggestions">
            <div class="search-suggestions-header">
              <span>搜索历史</span>
              <el-button size="mini" type="text" @click="clearSearchHistory">
                <i class="el-icon-delete" /> 清空
              </el-button>
            </div>
            <div class="search-suggestion-list">
              <div
                v-for="(item, index) in searchHistory"
                :key="index"
                class="search-suggestion-item"
                @click="selectSearchHistory(item)"
              >
                <i class="el-icon-time" />
                <span class="suggestion-text">{{ item.query }}</span>
                <span class="suggestion-count">{{ item.count }} 个匹配</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 代码编辑器 -->
        <div class="code-editor-container">
          <textarea
            ref="codeEditor"
            v-model="htmlContent"
            class="code-editor"
            :class="{ 'has-selection': selectedText }"
            placeholder="请输入HTML代码..."
            @mouseup="handleTextSelection"
            @keyup="handleTextSelection"
            @keydown="handleKeyDown"
            @focus="handleEditorFocus"
            @blur="handleEditorBlur"
            @input="updatePreview"
          />
        </div>

        <!-- AI修改功能区域 -->
        <div class="ai-section" :class="{ 'has-selected-code': selectedText }">
          <div class="ai-header">
            <div class="ai-header-left">
              <h5>AI智能修改</h5>
              <div class="selection-status">
                <el-tag v-if="selectedText" size="small" type="success" effect="dark">
                  <i class="el-icon-edit-outline" />
                  已选择 {{ selectedText.length }} 字符代码
                </el-tag>
                <el-tag v-else size="small" type="info" effect="plain">
                  <i class="el-icon-document" />
                  将修改全部代码
                </el-tag>
              </div>
            </div>
            <div class="ai-header-right">
              <el-button
                v-if="selectedText"
                size="mini"
                type="danger"
                plain
                icon="el-icon-refresh-left"
                title="清除所有选择的代码"
                @click="clearSelection"
              >
                清除选择
              </el-button>
            </div>
          </div>

          <div class="ai-input-area">
            <!-- 选择代码提示区域 -->
            <div v-if="selectedText" class="selected-code-display">
              <div class="selected-code-header">
                <i class="el-icon-view" />
                <span>将修改以下选中的代码：</span>
              </div>
              <div class="selected-code-content">
                <pre class="code-preview">{{ selectedText }}</pre>
              </div>
            </div>

            <el-input
              v-model="aiPrompt"
              type="textarea"
              :rows="3"
              :placeholder="getAiInputPlaceholder()"
              class="ai-prompt-input"
              :class="{ 'with-selection': selectedText }"
            />

            <div class="ai-controls">
              <div class="ai-options">
                <el-checkbox v-model="aiOptions.preserveStructure">保持HTML结构</el-checkbox>
                <el-checkbox v-model="aiOptions.modernStyle">现代化样式</el-checkbox>
                <el-checkbox v-model="aiOptions.responsive">响应式设计</el-checkbox>
              </div>

              <div class="ai-buttons">
                <el-button size="small" @click="clearAiInput">清空输入</el-button>
                <el-button
                  size="small"
                  :type="selectedText ? 'success' : 'primary'"
                  :loading="aiProcessing"
                  :disabled="!aiPrompt.trim()"
                  class="ai-modify-btn"
                  :class="{ 'with-selection': selectedText }"
                  @click="aiModifyCode"
                >
                  <i class="el-icon-magic-stick" />
                  {{ selectedText ? `AI修改选中代码 (${selectedText.length}字符)` : 'AI修改全部代码' }}
                </el-button>
              </div>
            </div>
          </div>

          <!-- AI处理进度 -->
          <div v-if="aiProcessing" class="ai-progress">
            <el-progress
              :percentage="aiProgress"
              :status="aiProgress === 100 ? 'success' : ''"
              :show-text="false"
            />
            <p class="progress-text">{{ aiProgressText }}</p>
          </div>
        </div>
      </div>
    </div>

    <!-- AI Task 对话框 -->
    <AITask
      ref="aiTask"
      task-name="ai_modify_html_code"
      :params="aiTaskParams"
      :show-name="aiTaskShowName"
      dialog-title="AI修改HTML代码"
      dialog-width="80%"
      @final-result="handleAITaskResult"
      @close="handleAITaskClose"
    />
  </div>
</template>

<script>
import { updateStaticSiteCategory } from '@/api/spider/static_site'
import AITask from '@/components/AITask'

export default {
  name: 'CategoryPreviewEditor',
  components: {
    AITask
  },
  data() {
    return {
      // 基本信息
      categoryId: null,
      categoryName: '',
      siteId: null,
      siteName: '',

      // 代码内容
      htmlContent: '',
      originalContent: '',

      // 预览相关
      previewHtml: '',
      viewportMode: 'desktop',

      // 代码选择
      selectedText: '',
      selectionStart: 0,
      selectionEnd: 0,

      // AI功能
      aiPrompt: '',
      aiProcessing: false,
      aiProgress: 0,
      aiProgressText: '',
      aiOptions: {
        preserveStructure: true,
        modernStyle: false,
        responsive: true
      },

      // UI状态
      saving: false,

      // 元素检查功能
      inspectMode: false,
      lastInspectedElement: null,

      // 搜索功能
      showSearch: false,
      searchQuery: '',
      searchMatches: [],
      currentSearchIndex: 0,
      searchHighlightedRanges: [],
      searchOptions: {
        caseSensitive: false,
        useRegex: false
      },
      searchHistory: [],
      showSuggestions: false,
      searchHistoryKey: 'category_editor_search_history'
    }
  },
  computed: {
    viewportClass() {
      return `viewport-${this.viewportMode}`
    },

    // AI Task 参数
    aiTaskParams() {
      return {
        task_name: 'ai_modify_html_code',
        user_prompt: this.aiPrompt,
        full_html_content: this.htmlContent,
        selected_code: this.selectedText || '',
        selection_start: this.selectionStart,
        selection_end: this.selectionEnd,
        preserve_structure: this.aiOptions.preserveStructure,
        modern_style: this.aiOptions.modernStyle,
        responsive: this.aiOptions.responsive,
        category_name: this.categoryName
      }
    },

    // AI Task 显示名称
    aiTaskShowName() {
      if (this.selectedText) {
        return `修改选中的 ${this.selectedText.length} 字符代码`
      } else {
        return '修改全部HTML代码'
      }
    }
  },
  created() {
    this.initializeEditor()
    this.loadSearchHistory()
  },
  mounted() {
    this.setupEditor()
    this.setupKeyboardShortcuts()
  },
  beforeDestroy() {
    // 清理事件监听器
    this.removeElementInspection()
    this.removeKeyboardShortcuts()
  },
  methods: {
    // 初始化编辑器
    initializeEditor() {
      // 从路由参数获取信息
      this.categoryId = this.$route.query.category_id
      this.categoryName = this.$route.query.category_name || '未知分类'
      this.siteId = this.$route.query.site_id
      this.siteName = this.$route.query.site_name || '未知网站'
      this.htmlContent = this.$route.query.html_content || ''
      this.originalContent = this.htmlContent

      // 初始化预览
      this.updatePreview()
    },

    // 设置键盘快捷键
    setupKeyboardShortcuts() {
      document.addEventListener('keydown', this.handleKeyboardShortcut)
    },

    // 移除键盘快捷键
    removeKeyboardShortcuts() {
      document.removeEventListener('keydown', this.handleKeyboardShortcut)
    },

    // 处理键盘快捷键
    handleKeyboardShortcut(event) {
      // Ctrl/Cmd + Shift + I 切换检查模式
      if ((event.ctrlKey || event.metaKey) && event.shiftKey && event.key === 'I') {
        event.preventDefault()
        this.toggleInspectMode()
      }
      // Esc 键退出检查模式
      if (event.key === 'Escape' && this.inspectMode) {
        event.preventDefault()
        this.toggleInspectMode()
      }
    },

    setupEditor() {
      // 可以在这里集成更高级的代码编辑器，如CodeMirror或Monaco Editor
      this.$nextTick(() => {
        if (this.$refs.codeEditor) {
          // 设置代码编辑器的一些属性
          this.$refs.codeEditor.style.fontFamily = 'Monaco, Menlo, "Ubuntu Mono", monospace'
          this.$refs.codeEditor.style.fontSize = '14px'
          this.$refs.codeEditor.style.lineHeight = '1.5'
        }
      })
    },

    // 文本选择处理
    handleTextSelection() {
      this.$nextTick(() => {
        const editor = this.$refs.codeEditor
        if (editor) {
          this.selectionStart = editor.selectionStart
          this.selectionEnd = editor.selectionEnd
          const newSelectedText = this.htmlContent.substring(this.selectionStart, this.selectionEnd)

          // 只有当选择的文本不为空时才更新
          if (newSelectedText.trim()) {
            this.selectedText = newSelectedText
          } else if (this.selectionStart === this.selectionEnd) {
            // 如果光标位置没有选择，清除选择状态
            this.selectedText = ''
          }
        }
      })
    },

    // 编辑器获取焦点
    handleEditorFocus() {
      // 当编辑器获取焦点时，可以做一些处理
    },

    // 编辑器失去焦点
    handleEditorBlur() {
      // 保持选择状态，不清除
      // 这样即使点击AI输入框，选择状态也会保持
    },

    // 清除选择
    clearSelection() {
      this.selectedText = ''
      this.selectionStart = 0
      this.selectionEnd = 0
      // 重新聚焦到编辑器
      this.$nextTick(() => {
        if (this.$refs.codeEditor) {
          this.$refs.codeEditor.focus()
        }
      })
    },

    // 获取AI输入框的占位符文本
    getAiInputPlaceholder() {
      if (this.selectedText) {
        return `描述您想要对选中代码段进行的修改，例如：
- 将按钮颜色改为蓝色
- 增加鼠标悬停效果  
- 调整字体大小为18px
- 添加圆角边框
- 优化布局样式`
      } else {
        return `描述您想要的修改内容，例如：
- 将按钮颜色改为蓝色
- 增加鼠标悬停效果
- 调整字体大小为18px  
- 添加圆角边框
- 优化整体布局`
      }
    },

    // 更新预览
    updatePreview() {
      let content = this.htmlContent || this.getDefaultContent()

      // 如果不是完整的HTML文档，包装一下
      if (content && !content.includes('<html>') && !content.includes('<!DOCTYPE')) {
        content = `
          <!DOCTYPE html>
          <html>
          <head>
            <meta charset="UTF-8">
            <meta name="viewport" content="width=device-width, initial-scale=1.0">
            <title>${this.categoryName} - 预览</title>
            <style>
              body { 
                font-family: Arial, sans-serif; 
                margin: 0; 
                padding: 20px; 
                line-height: 1.6; 
              }
              * { box-sizing: border-box; }
            </style>
          </head>
          <body>
            ${content}
          </body>
          </html>
        `
      }

      this.previewHtml = content

      // 预览更新后重新设置元素检查
      this.$nextTick(() => {
        setTimeout(() => {
          this.setupElementInspection()
        }, 100) // 稍微延迟以确保iframe内容完全加载
      })
    },

    getDefaultContent() {
      return `
        <div style="padding: 40px; text-align: center; color: #666; font-family: Arial, sans-serif;">
          <h2 style="color: #409EFF; margin-bottom: 20px;">分类预览</h2>
          <div style="background: #f5f7fa; padding: 20px; border-radius: 8px; margin-bottom: 20px;">
            <h3 style="margin-top: 0; color: #303133;">分类名称：${this.categoryName}</h3>
          </div>
          <div style="background: #fff3cd; padding: 15px; border-radius: 4px; border: 1px solid #ffeaa7;">
            <p style="margin: 0; color: #856404;">该分类暂无HTML内容，请在右侧编辑器中添加HTML内容。</p>
          </div>
        </div>
      `
    },

    // 视口切换
    setViewport(mode) {
      this.viewportMode = mode
    },

    // 刷新预览
    refreshPreview() {
      this.updatePreview()
    },

    // 预览加载完成
    onPreviewLoad() {
      // 预览框架加载完成后的处理
      this.setupElementInspection()
    },

    // 设置元素检查功能
    setupElementInspection() {
      try {
        const iframe = this.$refs.previewFrame
        if (iframe && iframe.contentDocument) {
          const doc = iframe.contentDocument

          // 移除之前的事件监听（如果有的话）
          this.removeElementInspection()

          // 添加鼠标悬停和点击事件
          doc.addEventListener('mouseover', this.handleElementHover, true)
          doc.addEventListener('mouseout', this.handleElementMouseOut, true)
          doc.addEventListener('click', this.handleElementClick, true)
          doc.addEventListener('dblclick', this.handleElementDoubleClick, true)

          // 添加样式
          this.addInspectionStyles(doc)
        }
      } catch (error) {
        console.log('设置元素检查失败:', error)
      }
    },

    // 移除元素检查功能
    removeElementInspection() {
      try {
        const iframe = this.$refs.previewFrame
        if (iframe && iframe.contentDocument) {
          const doc = iframe.contentDocument
          doc.removeEventListener('mouseover', this.handleElementHover, true)
          doc.removeEventListener('mouseout', this.handleElementMouseOut, true)
          doc.removeEventListener('click', this.handleElementClick, true)
          doc.removeEventListener('dblclick', this.handleElementDoubleClick, true)
        }
      } catch (error) {
        console.log('移除元素检查失败:', error)
      }
    },

    // 添加检查样式
    addInspectionStyles(doc) {
      let style = doc.getElementById('inspection-styles')
      if (!style) {
        style = doc.createElement('style')
        style.id = 'inspection-styles'
        style.textContent = `
          .element-hover-highlight {
            outline: 2px solid #409eff !important;
            outline-offset: 1px !important;
            cursor: crosshair !important;
            position: relative !important;
          }
          .element-hover-highlight::before {
            content: attr(data-tag-info);
            position: absolute;
            top: -25px;
            left: 0;
            background: #409eff;
            color: white;
            padding: 2px 6px;
            font-size: 12px;
            border-radius: 3px;
            white-space: nowrap;
            z-index: 9999;
            pointer-events: none;
          }
          .element-click-highlight {
            outline: 3px solid #67c23a !important;
            outline-offset: 1px !important;
            animation: element-selected 0.5s ease;
          }
          @keyframes element-selected {
            0% { outline-color: #67c23a; }
            50% { outline-color: #f56c6c; }
            100% { outline-color: #67c23a; }
          }
        `
        doc.head.appendChild(style)
      }
    },

    // 处理元素悬停
    handleElementHover(event) {
      if (!this.inspectMode) return

      const element = event.target
      if (element && element.tagName) {
        // 移除其他元素的高亮
        this.clearElementHighlight(event.target.ownerDocument)

        // 添加当前元素的高亮
        element.classList.add('element-hover-highlight')

        // 设置标签信息
        const tagInfo = this.getElementTagInfo(element)
        element.setAttribute('data-tag-info', tagInfo)
      }
    },

    // 处理元素鼠标离开
    handleElementMouseOut(event) {
      if (!this.inspectMode) return

      const element = event.target
      if (element && element.classList) {
        element.classList.remove('element-hover-highlight')
        element.removeAttribute('data-tag-info')
      }
    },

    // 处理元素点击
    handleElementClick(event) {
      if (!this.inspectMode) return

      event.preventDefault()
      event.stopPropagation()

      const element = event.target
      if (element && element.tagName) {
        // 检查是否是同一个元素的重复点击
        const isSameElement = this.lastInspectedElement === element
        this.lastInspectedElement = element

        // 高亮被点击的元素
        this.highlightClickedElement(element)

        // 定位到代码
        this.locateElementInCode(element, isSameElement)
      }
    },

    // 处理元素双击
    handleElementDoubleClick(event) {
      if (!this.inspectMode) return

      event.preventDefault()
      event.stopPropagation()

      const element = event.target
      if (element && element.tagName) {
        // 快速编辑模式：定位到代码并自动开启AI修改
        this.locateElementInCode(element)

        // 自动填入AI提示
        this.aiPrompt = `修改这个 ${element.tagName.toLowerCase()} 元素的样式和内容`

        // 显示提示
        this.$message({
          type: 'success',
          message: '🚀 快速编辑模式：已定位代码并填入AI提示',
          duration: 3000
        })

        // 聚焦到AI输入框
        this.$nextTick(() => {
          const aiInput = document.querySelector('.ai-prompt-input textarea')
          if (aiInput) {
            aiInput.focus()
          }
        })
      }
    },

    // 高亮被点击的元素
    highlightClickedElement(element) {
      // 移除悬停高亮
      element.classList.remove('element-hover-highlight')

      // 移除之前的点击高亮
      const doc = element.ownerDocument
      const clickHighlighted = doc.querySelectorAll('.element-click-highlight')
      clickHighlighted.forEach(el => el.classList.remove('element-click-highlight'))

      // 添加点击高亮
      element.classList.add('element-click-highlight')

      // 3秒后移除高亮
      setTimeout(() => {
        if (element.classList) {
          element.classList.remove('element-click-highlight')
        }
      }, 3000)
    },

    // 清除元素高亮
    clearElementHighlight(doc) {
      const highlighted = doc.querySelectorAll('.element-hover-highlight')
      highlighted.forEach(el => {
        el.classList.remove('element-hover-highlight')
        el.removeAttribute('data-tag-info')
      })
    },

    // 获取元素标签信息
    getElementTagInfo(element) {
      let info = element.tagName.toLowerCase()

      if (element.id) {
        info += `#${element.id}`
      }

      if (element.className && typeof element.className === 'string') {
        const classes = element.className.split(' ').filter(cls =>
          cls && !cls.includes('element-') && !cls.includes('highlight')
        )
        if (classes.length > 0) {
          info += `.${classes.slice(0, 2).join('.')}`
          if (classes.length > 2) info += '...'
        }
      }

      // 添加兄弟索引信息
      const parent = element.parentNode
      if (parent) {
        const siblings = Array.from(parent.children)
          .filter(sibling => sibling.tagName === element.tagName)

        if (siblings.length > 1) {
          const index = siblings.indexOf(element) + 1
          info += `:nth(${index}/${siblings.length})`
        }
      }

      return info
    },

    // 在代码中定位元素
    locateElementInCode(element, isSameElement = false) {
      try {
        // 获取元素的特征信息
        const elementInfo = this.getElementSearchInfo(element)

        // 在HTML代码中搜索匹配的位置
        const codePosition = this.findElementInCode(elementInfo)

        if (codePosition !== -1) {
          // 滚动到对应位置并高亮
          this.scrollToCodePosition(codePosition)

          // 显示成功消息
          const beforeText = this.htmlContent.substring(0, codePosition)
          const lineNumber = beforeText.split('\n').length

          // 验证定位准确性
          const verificationResult = this.verifyElementPosition(elementInfo, codePosition, lineNumber)

          if (isSameElement) {
            // 重复点击同一元素，显示更详细信息
            this.showElementDetails(elementInfo, lineNumber)
          } else {
            let message = `✅ 已定位到 ${elementInfo.tagName} 元素 (第${lineNumber}行)`
            if (verificationResult.confidence < 0.8) {
              message += ` [置信度: ${Math.round(verificationResult.confidence * 100)}%]`
            }
            this.$message.success(message)
          }
        } else {
          this.$message.warning(`未能在代码中找到对应的 ${elementInfo.tagName} 元素`)
        }
      } catch (error) {
        console.log('定位元素失败:', error)
        this.$message.error('定位元素失败')
      }
    },

    // 显示元素详细信息
    showElementDetails(elementInfo, lineNumber) {
      const details = []

      // 最重要的信息：完整开始标签
      if (elementInfo.startTag) {
        details.push(`🎯 完整标签: ${elementInfo.startTag}`)
      } else {
        details.push(`标签: ${elementInfo.tagName.toUpperCase()}`)
      }

      if (elementInfo.id) {
        details.push(`🔖 ID: ${elementInfo.id}`)
      }

      if (elementInfo.className) {
        const classes = elementInfo.className.split(' ').filter(cls =>
          cls && !cls.includes('element-') && !cls.includes('highlight')
        )
        if (classes.length > 0) {
          details.push(`🏷️ 类名: ${classes.slice(0, 3).join(', ')}${classes.length > 3 ? '...' : ''}`)
        }
      }

      if (elementInfo.parentInfo) {
        details.push(`📁 父元素: ${elementInfo.parentInfo.tagName}${elementInfo.parentInfo.id ? '#' + elementInfo.parentInfo.id : ''}`)
      }

      if (elementInfo.siblingIndex !== undefined) {
        details.push(`📊 位置: 第${elementInfo.siblingIndex + 1}个${elementInfo.tagName}`)
      }

      if (elementInfo.textContent) {
        details.push(`📝 文本: ${elementInfo.textContent.substring(0, 30)}${elementInfo.textContent.length > 30 ? '...' : ''}`)
      }

      details.push(`📍 代码位置: 第${lineNumber}行`)

      this.$notify({
        title: '🔍 元素详细信息',
        message: details.join('\n'),
        type: 'info',
        duration: 8000,
        dangerouslyUseHTMLString: false
      })
    },

    // 获取元素搜索信息
    getElementSearchInfo(element) {
      return {
        tagName: element.tagName.toLowerCase(),
        id: element.id || '',
        className: element.className || '',
        textContent: element.textContent ? element.textContent.trim().substring(0, 50) : '',
        innerHTML: element.innerHTML ? element.innerHTML.trim().substring(0, 100) : '',
        attributes: this.getElementAttributes(element),
        outerHTML: element.outerHTML || '',
        startTag: this.getElementStartTag(element),
        normalizedStartTag: this.getNormalizedStartTag(element),
        siblingIndex: this.getSiblingIndex(element),
        parentInfo: this.getParentInfo(element)
      }
    },

    // 获取元素的开始标签
    getElementStartTag(element) {
      const outerHTML = element.outerHTML || ''
      const match = outerHTML.match(/^<[^>]+>/)
      return match ? match[0] : ''
    },

    // 获取标准化的开始标签（用于匹配）
    getNormalizedStartTag(element) {
      let tag = `<${element.tagName.toLowerCase()}`

      // 获取所有属性并排序（确保一致的顺序）
      const attributes = []

      if (element.attributes) {
        for (let i = 0; i < element.attributes.length; i++) {
          const attr = element.attributes[i]
          if (!attr.name.startsWith('data-tag-info') && !attr.name.includes('highlight')) {
            attributes.push({
              name: attr.name,
              value: attr.value
            })
          }
        }
      }

      // 按属性名排序
      attributes.sort((a, b) => a.name.localeCompare(b.name))

      // 构建标签字符串
      for (const attr of attributes) {
        tag += ` ${attr.name}="${attr.value}"`
      }

      tag += '>'

      return tag
    },

    // 获取兄弟元素中的索引
    getSiblingIndex(element) {
      const parent = element.parentNode
      if (!parent) return 0

      const siblings = Array.from(parent.children)
        .filter(sibling => sibling.tagName === element.tagName)

      return siblings.indexOf(element)
    },

    // 获取父元素信息
    getParentInfo(element) {
      const parent = element.parentNode
      if (!parent || parent.tagName === 'BODY') return null

      return {
        tagName: parent.tagName.toLowerCase(),
        id: parent.id || '',
        className: parent.className || '',
        textContent: parent.textContent ? parent.textContent.trim().substring(0, 30) : ''
      }
    },

    // 获取元素属性
    getElementAttributes(element) {
      const attrs = {}
      if (element.attributes) {
        for (let i = 0; i < element.attributes.length; i++) {
          const attr = element.attributes[i]
          if (!attr.name.startsWith('data-tag-info') && !attr.name.includes('highlight')) {
            attrs[attr.name] = attr.value
          }
        }
      }
      return attrs
    },

    // 在代码中查找元素
    findElementInCode(elementInfo) {
      console.log('开始搜索元素:', elementInfo)
      console.log('完整开始标签:', elementInfo.startTag)
      console.log('标准化标签:', elementInfo.normalizedStartTag)

      const code = this.htmlContent
      const lines = code.split('\n')

      // 1. 最高优先级：完整开始标签精确匹配
      if (elementInfo.startTag) {
        const exactPosition = this.findByExactTag(elementInfo.startTag, lines)
        if (exactPosition !== -1) {
          console.log('✅ 通过完整标签精确匹配找到位置:', exactPosition)
          return exactPosition
        }
      }

      // 2. 标准化标签匹配（处理属性顺序差异）
      if (elementInfo.normalizedStartTag) {
        const normalizedPosition = this.findByNormalizedTag(elementInfo, lines)
        if (normalizedPosition !== -1) {
          console.log('✅ 通过标准化标签匹配找到位置:', normalizedPosition)
          return normalizedPosition
        }
      }

      // 3. ID匹配（作为备用方案）
      if (elementInfo.id) {
        const position = this.findByUniqueAttribute('id', elementInfo.id, elementInfo.tagName, lines)
        if (position !== -1) {
          console.log('✅ 通过ID备用匹配找到位置:', position)
          return position
        }
      }

      console.log('❌ 未找到匹配的元素')
      return -1
    },

    // 通过完整标签精确匹配
    findByExactTag(startTag, lines) {
      for (let i = 0; i < lines.length; i++) {
        const line = lines[i].trim()

        // 精确匹配完整标签
        if (line.includes(startTag.trim())) {
          console.log(`精确匹配第${i + 1}行:`, line)
          return this.getCharacterPosition(lines, i)
        }
      }

      return -1
    },

    // 通过标准化标签匹配（处理属性顺序问题）
    findByNormalizedTag(elementInfo, lines) {
      const tagName = elementInfo.tagName
      const attributes = elementInfo.attributes || {}

      for (let i = 0; i < lines.length; i++) {
        const line = lines[i]

        // 检查是否包含目标标签名
        const tagPattern = new RegExp(`<${tagName}(?:\\s|>)`, 'i')
        if (!tagPattern.test(line)) {
          continue
        }

        // 检查标签中的所有关键属性
        let allAttributesMatch = true
        let attributeCount = 0

        for (const [attrName, attrValue] of Object.entries(attributes)) {
          if (attrName && attrValue && attrName !== 'class') {
            const attrPattern = new RegExp(`\\s${attrName}=['"]${this.escapeRegExp(attrValue)}['"]`, 'i')
            if (attrPattern.test(line)) {
              attributeCount++
            } else {
              allAttributesMatch = false
              break
            }
          }
        }

        // 特殊处理class属性（可能有多个类名）
        if (allAttributesMatch && elementInfo.className) {
          const classes = elementInfo.className.split(' ').filter(cls =>
            cls && !cls.includes('element-') && !cls.includes('highlight')
          )

          if (classes.length > 0) {
            // 检查主要类名是否存在
            const mainClass = classes[0]
            const classPattern = new RegExp(`\\sclass=['"][^'"]*\\b${this.escapeRegExp(mainClass)}\\b[^'"]*['"]`, 'i')

            if (!classPattern.test(line)) {
              allAttributesMatch = false
            }
          }
        }

        // 如果所有属性都匹配，认为找到了目标元素
        if (allAttributesMatch && (attributeCount > 0 || elementInfo.className)) {
          console.log(`标准化匹配第${i + 1}行:`, line.trim())
          return this.getCharacterPosition(lines, i)
        }
      }

      return -1
    },

    // 通过唯一属性查找
    findByUniqueAttribute(attrName, attrValue, tagName, lines) {
      const pattern = new RegExp(`<${tagName}[^>]*\\s${attrName}=['"]${this.escapeRegExp(attrValue)}['"]`, 'i')

      for (let i = 0; i < lines.length; i++) {
        if (pattern.test(lines[i])) {
          return this.getCharacterPosition(lines, i)
        }
      }
      return -1
    },

    // 转义正则表达式特殊字符
    escapeRegExp(string) {
      return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
    },

    // 验证元素定位的准确性
    verifyElementPosition(elementInfo, codePosition, lineNumber) {
      const lines = this.htmlContent.split('\n')
      const targetLine = lines[lineNumber - 1] || ''

      let confidence = 0
      const checks = []

      // 1. 最高优先级：完整标签匹配
      if (elementInfo.startTag && targetLine.includes(elementInfo.startTag.trim())) {
        confidence = 1.0
        checks.push('✅ 完整标签精确匹配')

        console.log(`🎯 完美匹配! 置信度: 100%`)
        console.log(`目标标签: ${elementInfo.startTag}`)
        console.log(`目标行: ${targetLine.trim()}`)

        return {
          confidence: confidence,
          checks: checks,
          targetLine: targetLine.trim(),
          matchType: 'exact_tag'
        }
      }

      // 2. 检查标签名
      if (targetLine.toLowerCase().includes(`<${elementInfo.tagName.toLowerCase()}`)) {
        confidence += 0.3
        checks.push('标签名匹配')
      }

      // 3. 检查ID（高权重）
      if (elementInfo.id && targetLine.includes(`id="${elementInfo.id}"`)) {
        confidence += 0.5
        checks.push('ID匹配')
      }

      // 4. 检查主要类名
      if (elementInfo.className) {
        const classes = elementInfo.className.split(' ').filter(cls =>
          cls && !cls.includes('element-') && !cls.includes('highlight')
        )

        let classMatches = 0
        for (const cls of classes) {
          if (targetLine.includes(cls)) {
            classMatches++
          }
        }

        if (classMatches > 0) {
          confidence += 0.2 * (classMatches / classes.length)
          checks.push(`类名匹配(${classMatches}/${classes.length})`)
        }
      }

      // 5. 检查其他属性
      if (elementInfo.attributes) {
        let attrMatches = 0
        const totalAttrs = Object.keys(elementInfo.attributes).filter(name => name !== 'class' && name !== 'id').length

        for (const [attrName, attrValue] of Object.entries(elementInfo.attributes)) {
          if (attrName !== 'class' && attrName !== 'id' && attrValue && targetLine.includes(`${attrName}="${attrValue}"`)) {
            attrMatches++
          }
        }

        if (attrMatches > 0 && totalAttrs > 0) {
          confidence += 0.1 * (attrMatches / totalAttrs)
          checks.push(`属性匹配(${attrMatches}/${totalAttrs})`)
        }
      }

      const finalConfidence = Math.min(confidence, 1.0)
      const confidencePercent = Math.round(finalConfidence * 100)

      console.log(`定位验证 - 置信度: ${confidencePercent}%, 检查项: ${checks.join(', ')}`)
      console.log(`目标行内容: ${targetLine.trim()}`)

      return {
        confidence: finalConfidence,
        checks: checks,
        targetLine: targetLine.trim(),
        matchType: finalConfidence === 1.0 ? 'perfect' : finalConfidence >= 0.8 ? 'good' : 'partial'
      }
    },

    // 获取字符位置
    getCharacterPosition(lines, lineIndex) {
      let position = 0
      for (let i = 0; i < lineIndex; i++) {
        position += lines[i].length + 1 // +1 for newline
      }
      return position
    },

    // 滚动到代码位置
    scrollToCodePosition(position) {
      const editor = this.$refs.codeEditor
      if (editor) {
        // 首先设置光标位置
        editor.focus()
        editor.setSelectionRange(position, position)

        // 计算行号
        const beforeText = this.htmlContent.substring(0, position)
        const lineNumber = beforeText.split('\n').length

        // 精确滚动到目标行
        this.scrollToLineAccurate(editor, lineNumber, position)

        // 高亮选择对应的代码段
        this.highlightTargetCode(editor, position)

        console.log(`定位成功: 行号 ${lineNumber}, 字符位置 ${position}`)
      }
    },

    // 精确滚动到指定行
    scrollToLineAccurate(editor, lineNumber, charPosition) {
      // 获取实际的行高
      const computedStyle = window.getComputedStyle(editor)
      const fontSize = parseFloat(computedStyle.fontSize) || 14
      const lineHeight = parseFloat(computedStyle.lineHeight) || fontSize * 1.6

      const editorHeight = editor.clientHeight

      // 计算目标滚动位置，让目标行显示在编辑器顶部附近
      const targetLine = Math.max(1, lineNumber)

      // 让目标行显示在顶部附近（只留1行缓冲）
      const offsetFromTop = 1 // 只保留1行偏移，让目标行非常靠近顶部
      const targetScrollLine = Math.max(0, targetLine - offsetFromTop)

      // 修正后的滚动位置计算
      const targetScrollTop = Math.max(0, targetScrollLine * lineHeight)

      // 确保不超出最大滚动范围
      const maxScrollTop = Math.max(0, editor.scrollHeight - editorHeight)
      const finalScrollTop = Math.min(targetScrollTop, maxScrollTop)

      // 使用动画滚动到目标位置
      this.animateScrollTo(editor, finalScrollTop)

      console.log(`滚动参数: 行高=${lineHeight}, 目标行=${targetLine}, 偏移=${offsetFromTop}, 滚动到=${finalScrollTop}, 最大滚动=${maxScrollTop}`)
    },

    // 动画滚动到目标位置
    animateScrollTo(element, targetScrollTop) {
      const startScrollTop = element.scrollTop
      const distance = targetScrollTop - startScrollTop
      const duration = 300 // 300ms动画
      const startTime = performance.now()

      const animateScroll = (currentTime) => {
        const elapsed = currentTime - startTime
        const progress = Math.min(elapsed / duration, 1)

        // 使用缓动函数
        const easeProgress = this.easeInOutCubic(progress)
        const currentScrollTop = startScrollTop + (distance * easeProgress)

        element.scrollTop = currentScrollTop

        if (progress < 1) {
          requestAnimationFrame(animateScroll)
        }
      }

      requestAnimationFrame(animateScroll)
    },

    // 缓动函数
    easeInOutCubic(t) {
      return t < 0.5 ? 4 * t * t * t : 1 - Math.pow(-2 * t + 2, 3) / 2
    },

    // 高亮目标代码
    highlightTargetCode(editor, position) {
      // 找到当前行的开始和结束位置
      const lines = this.htmlContent.split('\n')
      const beforeText = this.htmlContent.substring(0, position)
      const lineNumber = beforeText.split('\n').length

      // 计算当前行的字符范围
      let lineStartPos = 0
      for (let i = 0; i < lineNumber - 1; i++) {
        lineStartPos += lines[i].length + 1 // +1 for newline
      }

      const currentLine = lines[lineNumber - 1] || ''
      const lineEndPos = lineStartPos + currentLine.length

      // 尝试找到更精确的元素标签范围
      const elementRange = this.findElementTagRange(position)

      if (elementRange.start !== -1 && elementRange.end !== -1) {
        // 选择整个元素标签
        editor.setSelectionRange(elementRange.start, elementRange.end)
        this.selectedText = this.htmlContent.substring(elementRange.start, elementRange.end)
        this.selectionStart = elementRange.start
        this.selectionEnd = elementRange.end

        this.$message.success(`已选择并定位到元素标签 (${elementRange.end - elementRange.start} 字符)`)
      } else {
        // 选择整行
        editor.setSelectionRange(lineStartPos, lineEndPos)
        this.selectedText = currentLine
        this.selectionStart = lineStartPos
        this.selectionEnd = lineEndPos

        this.$message.success(`已选择并定位到第 ${lineNumber} 行`)
      }
    },

    // 查找元素标签的完整范围
    findElementTagRange(position) {
      const content = this.htmlContent
      let start = position
      let end = position

      // 向前找到 < 符号
      while (start > 0 && content[start] !== '<') {
        start--
      }

      // 向后找到 > 符号
      while (end < content.length && content[end] !== '>') {
        end++
      }

      // 如果找到完整的标签，返回范围
      if (start >= 0 && end < content.length && content[start] === '<' && content[end] === '>') {
        return { start: start, end: end + 1 }
      }

      return { start: -1, end: -1 }
    },

    // 切换检查模式
    toggleInspectMode() {
      this.inspectMode = !this.inspectMode

      if (this.inspectMode) {
        this.$message({
          type: 'success',
          duration: 4000,
          dangerouslyUseHTMLString: true,
          message: `
            <div>
              <strong>✨ 元素检查模式已开启！</strong><br>
              • 悬停预览元素查看标签信息<br>
              • 单击元素自动定位到代码<br>
              • 双击元素快速编辑（自动填入AI提示）<br>
              • 重复点击查看元素详情<br>
              • 快捷键: <code>Esc</code> 退出，<code>Ctrl+Shift+I</code> 切换
            </div>
          `
        })
      } else {
        this.$message.info('元素检查模式已关闭')
        // 清除所有高亮
        try {
          const iframe = this.$refs.previewFrame
          if (iframe && iframe.contentDocument) {
            this.clearElementHighlight(iframe.contentDocument)
          }
        } catch (error) {
          console.log('清除高亮失败:', error)
        }
      }
    },

    // 格式化代码
    formatCode() {
      try {
        // 简单的HTML格式化（可以集成更强大的格式化库）
        const formatted = this.htmlContent
          .replace(/></g, '>\n<')
          .replace(/\n\s*\n/g, '\n')

        // 添加缩进
        let indentLevel = 0
        const lines = formatted.split('\n')
        const formattedLines = lines.map(line => {
          const trimmed = line.trim()
          if (trimmed.startsWith('</')) {
            indentLevel--
          }
          const indented = '  '.repeat(Math.max(0, indentLevel)) + trimmed
          if (trimmed.startsWith('<') && !trimmed.startsWith('</') && !trimmed.endsWith('/>')) {
            indentLevel++
          }
          return indented
        })

        this.htmlContent = formattedLines.join('\n')
        this.updatePreview()
        this.$message.success('代码格式化完成')
      } catch (error) {
        this.$message.error('代码格式化失败：' + error.message)
      }
    },

    // 重置代码
    resetCode() {
      this.$confirm('确定要重置为原始代码吗？当前的修改将丢失。', '确认重置', {
        type: 'warning'
      }).then(() => {
        this.htmlContent = this.originalContent
        this.updatePreview()
        this.$message.success('代码已重置')
      }).catch(() => {})
    },

    // 保存代码
    async saveCode() {
      if (!this.categoryId) {
        this.$message.error('缺少分类ID')
        return
      }

      this.saving = true
      try {
        const data = {
          id: this.categoryId,
          html_content: this.htmlContent,
          site: this.siteId
        }

        const response = await updateStaticSiteCategory(this.categoryId, data)

        if (response.success) {
          this.originalContent = this.htmlContent
          this.$message.success('保存成功')
        } else {
          this.$message.error('保存失败：' + response.msg)
        }
      } catch (error) {
        this.$message.error('保存失败：' + (error.response?.data?.msg || error.message))
      } finally {
        this.saving = false
      }
    },

    // AI修改代码
    async aiModifyCode() {
      console.log('aiModifyCode 被调用')
      if (!this.aiPrompt.trim()) {
        this.$message.error('请输入修改要求')
        return
      }

      console.log('准备显示 AI Task 对话框')
      // 使用 AITASK 插件进行流式处理
      this.showAITaskDialog()
    },

    // 显示 AI Task 对话框
    showAITaskDialog() {
      console.log('showAITaskDialog 被调用')
      console.log('$refs:', this.$refs)
      console.log('$refs.aiTask:', this.$refs.aiTask)

      // 使用 $nextTick 确保组件已渲染
      this.$nextTick(() => {
        console.log('$nextTick 回调执行')
        if (this.$refs.aiTask) {
          console.log('找到 aiTask 组件，调用 handleShowDialog')
          this.$refs.aiTask.handleShowDialog()
        } else {
          console.error('未找到 aiTask 组件引用')
        }
      })
    },

    // 处理 AI Task 的最终结果
    handleAITaskResult(result) {
      try {
        console.log('收到AI最终结果:', result)

        // 直接使用 AI 返回的最终结果
        let modifiedHtml = result

        // 如果结果是对象，优先使用 content 字段
        if (typeof result === 'object' && result !== null) {
          modifiedHtml = result.content || result.response || result.data || result.html_content || result
        }

        // 确保我们得到的是字符串格式的HTML
        if (typeof modifiedHtml !== 'string') {
          modifiedHtml = String(modifiedHtml)
        }

        // 清理HTML代码中的标记 - 更简洁的处理
        modifiedHtml = modifiedHtml
          .replace(/^```(?:html|xml)?\s*/, '') // 移除开始的 ```html 或 ```xml
          .replace(/\s*```$/, '') // 移除结束的 ```
          .replace(/<!--[\s\S]*?-->/g, '') // 移除HTML注释
          .trim()

        console.log('最终HTML内容长度:', modifiedHtml.length)
        console.log('最终HTML内容预览:', modifiedHtml.substring(0, 300))

        // 应用修改后的 HTML 代码到编辑区域
        if (modifiedHtml && modifiedHtml.length > 0) {
          this.htmlContent = modifiedHtml
          this.updatePreview()

          // 显示成功消息
          this.$message.success('✅ AI修改已应用到编辑区域')

          // 记录修改历史
          this.recordModificationHistory(this.aiPrompt, modifiedHtml)

          // 清除选择状态，准备下一次修改
          this.selectedText = ''
          this.selectionStart = 0
          this.selectionEnd = 0

          // 清空AI输入框，准备下一次输入
          this.aiPrompt = ''
        } else {
          console.warn('AI返回了空内容:', result)
          this.$message.warning('AI返回了空内容，请重试')
        }
      } catch (error) {
        console.error('处理 AI 结果时出错:', error)
        this.$message.error('处理 AI 结果时出错：' + error.message)
      }
    },

    // 处理非标准的 AI 响应
    handleNonStandardAIResponse(aiResponse) {
      // 可以在这里添加更多的解析逻辑
      console.log('AI 响应:', aiResponse)

      // 显示原始响应给用户参考
      this.$message.info('AI 修改完成，请查看对话框中的建议')
    },

    // 记录修改历史
    recordModificationHistory(prompt, modifiedHtml) {
      const historyItem = {
        timestamp: new Date().toISOString(),
        prompt: prompt,
        originalLength: this.htmlContent.length,
        modifiedLength: modifiedHtml.length,
        changeType: 'ai_modification'
      }

      // 可以在这里添加历史记录的存储逻辑
      console.log('修改历史记录:', historyItem)
    },

    // 处理 AI Task 对话框关闭
    handleAITaskClose() {
      // 清理相关状态
      this.aiPrompt = ''
    },

    // 保留原有的 AI 修改方法作为备用
    async aiModifyCodeLegacy() {
      if (!this.aiPrompt.trim()) {
        this.$message.error('请输入修改要求')
        return
      }

      this.aiProcessing = true
      this.aiProgress = 0
      this.aiProgressText = 'AI正在分析您的要求...'

      try {
        // 构建AI请求参数
        const requestData = {
          task_name: 'ai_modify_html_code',
          user_prompt: this.aiPrompt,
          full_html_content: this.htmlContent,
          selected_code: this.selectedText || '',
          selection_start: this.selectionStart,
          selection_end: this.selectionEnd,
          preserve_structure: this.aiOptions.preserveStructure,
          modern_style: this.aiOptions.modernStyle,
          responsive: this.aiOptions.responsive,
          category_name: this.categoryName
        }

        this.aiProgress = 30
        this.aiProgressText = 'AI正在生成修改方案...'

        // 调用AI修改接口
        const response = await this.callAiModifyApi(requestData)

        this.aiProgress = 70
        this.aiProgressText = 'AI正在应用修改...'

        if (response.success) {
          // 应用AI修改的结果
          this.applyAiModification(response.data)

          this.aiProgress = 100
          this.aiProgressText = 'AI修改完成！'

          setTimeout(() => {
            this.aiProcessing = false
            this.aiProgress = 0
            this.aiProgressText = ''
          }, 1000)

          this.$message.success('AI修改完成')
        } else {
          throw new Error(response.msg || 'AI修改失败')
        }
      } catch (error) {
        this.aiProcessing = false
        this.aiProgress = 0
        this.aiProgressText = ''
        this.$message.error('AI修改失败：' + error.message)
      }
    },

    // 调用AI修改API
    async callAiModifyApi(requestData) {
      try {
        // 调用真实的后端AI修改接口
        const { aiModifyHtmlCode } = await import('@/api/spider/static_site')
        const response = await aiModifyHtmlCode(requestData)

        // 检查响应格式并标准化
        if (response.success && response.data) {
          return {
            success: true,
            data: {
              modified_content: response.data.modified_content || response.modified_content,
              modification_description: response.data.modification_description || response.modification_description,
              changes_made: response.data.changes_made || response.changes_made || [],
              fallback_mode: response.data.fallback_mode || response.fallback_mode || false,
              selected_fragment: response.data.selected_fragment || response.selected_fragment || false,
              original_length: response.data.original_length || response.original_length,
              modified_length: response.data.modified_length || response.modified_length
            }
          }
        } else if (response.success) {
          // 处理扁平化的响应格式
          return {
            success: true,
            data: {
              modified_content: response.modified_content,
              modification_description: response.modification_description,
              changes_made: response.changes_made || [],
              fallback_mode: response.fallback_mode || false,
              selected_fragment: response.selected_fragment || false,
              original_length: response.original_length,
              modified_length: response.modified_length
            }
          }
        } else {
          throw new Error(response.msg || 'AI修改请求失败')
        }
      } catch (error) {
        // 如果真实API调用失败，使用fallback模拟
        console.log('AI API调用失败，使用fallback模式:', error)
        return new Promise((resolve) => {
          setTimeout(() => {
            // 模拟AI修改结果
            const mockResponse = {
              success: true,
              data: {
                modified_content: this.selectedText
                  ? this.htmlContent.substring(0, this.selectionStart) +
                  this.generateMockModification(this.selectedText) +
                  this.htmlContent.substring(this.selectionEnd)
                  : this.generateMockModification(this.htmlContent),
                modification_description: '已根据您的要求完成修改（本地模拟模式）',
                changes_made: [
                  '优化了样式设计',
                  '增强了用户体验',
                  '保持了原有结构'
                ],
                fallback_mode: true
              }
            }
            resolve(mockResponse)
          }, 1500)
        })
      }
    },

    // 生成模拟修改（临时方法，实际会被AI接口替代）
    generateMockModification(content) {
      // 更智能的模拟修改：根据用户的提示词进行相应的修改
      let modifiedContent = content
      const prompt = this.aiPrompt.toLowerCase()

      // 根据提示词进行不同的修改
      if (prompt.includes('颜色') || prompt.includes('color')) {
        // 修改颜色相关
        modifiedContent = modifiedContent.replace(
          /color:\s*[^;]+;/g,
          'color: #007bff;'
        )
      }

      if (prompt.includes('按钮') || prompt.includes('button')) {
        // 优化按钮样式
        modifiedContent = modifiedContent.replace(
          /<button([^>]*)>/g,
          '<button$1 style="background: linear-gradient(45deg, #007bff, #0056b3); border: none; border-radius: 6px; color: white; padding: 10px 20px; transition: transform 0.2s;" onmouseover="this.style.transform=\'scale(1.05)\'" onmouseout="this.style.transform=\'scale(1)\'">'
        )
      }

      if (prompt.includes('卡片') || prompt.includes('card')) {
        // 优化卡片样式
        modifiedContent = modifiedContent.replace(
          /<div([^>]*class="[^"]*card[^"]*"[^>]*)>/g,
          '<div$1 style="box-shadow: 0 4px 6px rgba(0,0,0,0.1); border-radius: 8px; transition: box-shadow 0.3s;" onmouseover="this.style.boxShadow=\'0 8px 15px rgba(0,0,0,0.2)\'" onmouseout="this.style.boxShadow=\'0 4px 6px rgba(0,0,0,0.1)\'">'
        )
      }

      if (prompt.includes('增加') || prompt.includes('添加') || prompt.includes('add')) {
        // 如果是增加内容，在选中文本后添加一些内容
        if (this.selectedText && prompt.includes('子项')) {
          const itemCount = prompt.match(/\d+/) ? parseInt(prompt.match(/\d+/)[0]) : 6
          let additionalItems = ''
          for (let i = 1; i <= itemCount; i++) {
            additionalItems += `\n    <li>新增子项 ${i}</li>`
          }
          modifiedContent = modifiedContent.replace(
            /<\/ul>/g,
            `${additionalItems}\n</ul>`
          )
        }
      }

      if (prompt.includes('字体') || prompt.includes('font')) {
        // 修改字体大小
        modifiedContent = modifiedContent.replace(
          /font-size:\s*[^;]+;/g,
          'font-size: 16px;'
        )
      }

      if (prompt.includes('边框') || prompt.includes('border')) {
        // 添加边框
        modifiedContent = modifiedContent.replace(
          /style="([^"]*)"/g,
          'style="$1 border: 1px solid #ddd; border-radius: 4px;"'
        )
      }

      // 如果没有匹配到特定的修改，进行通用的样式优化
      if (modifiedContent === content) {
        modifiedContent = modifiedContent.replace(
          /<div([^>]*)>/g,
          '<div$1 style="padding: 10px; margin: 5px 0; border-radius: 4px;">'
        )
      }

      return modifiedContent
    },

    // 应用AI修改结果
    applyAiModification(result) {
      // 检查是否有实际的内容修改
      if (result.modified_content) {
        this.htmlContent = result.modified_content
        this.updatePreview()

        // 清除选择状态，让用户看到完整的修改结果
        this.selectedText = ''
        this.selectionStart = 0
        this.selectionEnd = 0

        // 显示修改说明
        const title = result.fallback_mode ? 'AI修改完成（模拟模式）' : 'AI修改完成'
        const messageType = result.fallback_mode ? 'warning' : 'success'

        if (result.modification_description) {
          this.$notify({
            title: title,
            message: result.modification_description,
            type: messageType,
            duration: 4000
          })
        }

        // 显示具体的修改内容
        if (result.changes_made && result.changes_made.length > 0) {
          const changesList = result.changes_made.map(change => `• ${change}`).join('\n')
          const statusInfo = result.fallback_mode ? '\n\n⚠️ 注意：当前为模拟模式，请联系管理员配置AI服务' : ''

          this.$alert(changesList + statusInfo, '修改详情', {
            confirmButtonText: '确定',
            type: result.fallback_mode ? 'warning' : 'info'
          })
        }

        // 如果是fallback模式，显示额外提示
        if (result.fallback_mode) {
          this.$message({
            type: 'warning',
            message: '当前使用模拟模式，实际AI功能需要后端配置',
            duration: 5000
          })
        }

        // 统计信息
        if (result.original_length && result.modified_length) {
          const lengthDiff = result.modified_length - result.original_length
          const diffText = lengthDiff > 0 ? `增加了${lengthDiff}字符` : lengthDiff < 0 ? `减少了${Math.abs(lengthDiff)}字符` : '长度未变'
          console.log(`代码修改统计: 原长度${result.original_length}, 新长度${result.modified_length}, ${diffText}`)
        }
      } else {
        this.$message.error('AI修改失败：未返回修改内容')
      }
    },

    // 清空AI输入
    clearAiInput() {
      this.aiPrompt = ''
      // 可以选择是否清除选择状态
      // this.selectedText = ''
      // this.selectionStart = 0
      // this.selectionEnd = 0
    },

    // 关闭编辑器
    closeEditor() {
      if (this.htmlContent !== this.originalContent) {
        this.$confirm('有未保存的修改，确定要关闭吗？', '确认关闭', {
          type: 'warning'
        }).then(() => {
          this.$router.go(-1)
        }).catch(() => {})
      } else {
        this.$router.go(-1)
      }
    },

    // 搜索功能
    toggleSearch() {
      this.showSearch = !this.showSearch
      if (this.showSearch) {
        this.$nextTick(() => {
          if (this.$refs.searchInput) {
            this.$refs.searchInput.focus()
          }
        })
      } else {
        this.clearSearch()
      }
    },

    closeSearch() {
      this.showSearch = false
      this.showSuggestions = false
      this.clearSearch()
    },

    clearSearch() {
      this.searchQuery = ''
      this.searchMatches = []
      this.currentSearchIndex = 0
      this.clearSearchHighlights()
    },

    performSearch() {
      if (!this.searchQuery.trim()) {
        this.searchMatches = []
        this.currentSearchIndex = 0
        this.clearSearchHighlights()
        return
      }

      try {
        const matches = this.findMatches(this.searchQuery, this.htmlContent)
        this.searchMatches = matches
        this.currentSearchIndex = 0

        if (matches.length > 0) {
          this.highlightSearchResult(matches[0])
          // 保存到搜索历史
          this.saveToSearchHistory(this.searchQuery, matches.length)
        }
      } catch (error) {
        // 正则表达式错误
        this.$message.error('搜索表达式错误：' + error.message)
        this.searchMatches = []
        this.currentSearchIndex = 0
      }
    },

    findMatches(query, content) {
      const matches = []

      if (this.searchOptions.useRegex) {
        // 正则表达式搜索
        try {
          const flags = this.searchOptions.caseSensitive ? 'g' : 'gi'
          const regex = new RegExp(query, flags)
          let match

          while ((match = regex.exec(content)) !== null) {
            matches.push({
              start: match.index,
              end: match.index + match[0].length,
              lineNumber: this.getLineNumber(match.index)
            })

            // 防止无限循环
            if (regex.lastIndex === match.index) {
              regex.lastIndex++
            }
          }
        } catch (error) {
          throw new Error('正则表达式语法错误')
        }
      } else {
        // 普通文本搜索
        const searchContent = this.searchOptions.caseSensitive ? content : content.toLowerCase()
        const searchQuery = this.searchOptions.caseSensitive ? query : query.toLowerCase()

        let index = 0
        while ((index = searchContent.indexOf(searchQuery, index)) !== -1) {
          matches.push({
            start: index,
            end: index + searchQuery.length,
            lineNumber: this.getLineNumber(index)
          })
          index += searchQuery.length
        }
      }

      return matches
    },

    searchNext() {
      if (this.searchMatches.length === 0) return

      this.currentSearchIndex = (this.currentSearchIndex + 1) % this.searchMatches.length
      this.highlightSearchResult(this.searchMatches[this.currentSearchIndex])
    },

    searchPrevious() {
      if (this.searchMatches.length === 0) return

      this.currentSearchIndex = (this.currentSearchIndex - 1 + this.searchMatches.length) % this.searchMatches.length
      this.highlightSearchResult(this.searchMatches[this.currentSearchIndex])
    },

    highlightSearchResult(match) {
      const editor = this.$refs.codeEditor
      if (!editor) return

      // 滚动到匹配位置
      this.scrollToCodePosition(match.start)

      // 选中匹配的文本
      editor.focus()
      editor.setSelectionRange(match.start, match.end)

      // 更新状态
      this.selectedText = this.htmlContent.substring(match.start, match.end)
      this.selectionStart = match.start
      this.selectionEnd = match.end
    },

    clearSearchHighlights() {
      // 清除搜索高亮
      this.searchHighlightedRanges = []
    },

    getLineNumber(charPosition) {
      const beforeText = this.htmlContent.substring(0, charPosition)
      return beforeText.split('\n').length
    },

    // 处理键盘事件
    handleKeyDown(event) {
      // Ctrl+F 或 Cmd+F 打开搜索
      if ((event.ctrlKey || event.metaKey) && event.key === 'f') {
        event.preventDefault()
        this.toggleSearch()
      }
      // Esc 关闭搜索
      if (event.key === 'Escape' && this.showSearch) {
        this.closeSearch()
      }
      // F3 或 Ctrl+G 查找下一个
      if (event.key === 'F3' || ((event.ctrlKey || event.metaKey) && event.key === 'g')) {
        event.preventDefault()
        if (this.searchMatches.length > 0) {
          this.searchNext()
        }
      }
    },

    // 搜索选项切换
    toggleCaseSensitive() {
      this.searchOptions.caseSensitive = !this.searchOptions.caseSensitive
      if (this.searchQuery) {
        this.performSearch()
      }
    },

    toggleRegex() {
      this.searchOptions.useRegex = !this.searchOptions.useRegex
      if (this.searchQuery) {
        this.performSearch()
      }
    },

    // 搜索状态文本
    getSearchStatusText() {
      if (this.searchMatches.length === 0) {
        return this.searchQuery ? '未找到' : '0/0'
      }
      return `${this.currentSearchIndex + 1}/${this.searchMatches.length}`
    },

    // 搜索框焦点处理
    handleSearchFocus() {
      this.showSuggestions = true
    },

    handleSearchBlur() {
      // 延迟关闭建议，允许点击建议项
      setTimeout(() => {
        this.showSuggestions = false
      }, 200)
    },

    // 搜索历史管理
    loadSearchHistory() {
      try {
        const history = localStorage.getItem(this.searchHistoryKey)
        if (history) {
          this.searchHistory = JSON.parse(history)
        }
      } catch (error) {
        console.error('加载搜索历史失败:', error)
        this.searchHistory = []
      }
    },

    saveToSearchHistory(query, count) {
      // 移除重复项
      this.searchHistory = this.searchHistory.filter(item => item.query !== query)

      // 添加到开头
      this.searchHistory.unshift({
        query: query,
        count: count,
        timestamp: Date.now()
      })

      // 限制历史记录数量
      if (this.searchHistory.length > 10) {
        this.searchHistory = this.searchHistory.slice(0, 10)
      }

      // 保存到本地存储
      try {
        localStorage.setItem(this.searchHistoryKey, JSON.stringify(this.searchHistory))
      } catch (error) {
        console.error('保存搜索历史失败:', error)
      }
    },

    selectSearchHistory(item) {
      this.searchQuery = item.query
      this.showSuggestions = false
      this.performSearch()
    },

    clearSearchHistory() {
      this.searchHistory = []
      try {
        localStorage.removeItem(this.searchHistoryKey)
      } catch (error) {
        console.error('清除搜索历史失败:', error)
      }
    }
  }
}
</script>

<style scoped>
.preview-editor-container {
  height: 100vh;
  display: flex;
  flex-direction: column;
  background: #f5f7fa;
}

.toolbar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  background: white;
  border-bottom: 1px solid #e4e7ed;
  box-shadow: 0 1px 4px rgba(0,0,0,0.1);
}

.toolbar-actions {
  display: flex;
  gap: 8px;
}

.main-content {
  flex: 1;
  display: flex;
  min-height: 0;
}

.preview-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
  border-right: 1px solid #e4e7ed;
}

.editor-panel {
  flex: 1;
  display: flex;
  flex-direction: column;
  background: white;
}

.panel-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 20px;
  border-bottom: 1px solid #e4e7ed;
  background: #fafbfc;
}

.panel-header h4 {
  margin: 0;
  color: #303133;
  font-size: 16px;
  font-weight: 600;
}

.preview-controls,
.editor-controls {
  display: flex;
  align-items: center;
  gap: 12px;
}

.selection-info {
  font-size: 12px;
  color: #909399;
  padding: 4px 8px;
  background: #f0f9ff;
  border-radius: 4px;
}

.selection-hint {
  font-size: 12px;
  color: #909399;
  padding: 4px 8px;
  background: #f9f9f9;
  border-radius: 4px;
  border: 1px dashed #dcdfe6;
}

.selection-hint .el-icon-info {
  color: #409eff;
  margin-right: 4px;
}

.preview-content {
  flex: 1;
  padding: 20px;
  transition: all 0.3s ease;
}

.viewport-desktop .preview-content iframe {
  width: 100%;
  height: 100%;
}

.viewport-tablet .preview-content iframe {
  width: 768px;
  height: 100%;
  margin: 0 auto;
  display: block;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.viewport-mobile .preview-content iframe {
  width: 375px;
  height: 100%;
  margin: 0 auto;
  display: block;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.code-editor-container {
  flex: 1;
  padding: 20px;
  display: flex;
  flex-direction: column;
}

.code-editor {
  flex: 1;
  width: 100%;
  padding: 16px;
  border: 1px solid #dcdfe6;
  border-radius: 6px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 14px;
  line-height: 1.6;
  resize: none;
  outline: none;
  background: #fafafa;
}

.code-editor:focus {
  border-color: #409eff;
  box-shadow: 0 0 0 2px rgba(64, 158, 255, 0.2);
}

.code-editor.has-selection {
  border-color: #67c23a;
  box-shadow: 0 0 0 2px rgba(103, 194, 58, 0.2);
}

/* 代码编辑器平滑滚动 */
.code-editor {
  scroll-behavior: smooth;
}

/* 选中代码高亮效果 */
.code-editor::selection {
  background: rgba(103, 194, 58, 0.3);
  color: inherit;
}

.code-editor::-moz-selection {
  background: rgba(103, 194, 58, 0.3);
  color: inherit;
}

/* AI区域选择状态样式 */
.ai-section.has-selected-code {
  background: linear-gradient(135deg, #f8fffe, #f0f9ff);
  border-top: 2px solid #67c23a;
}

.selection-status {
  display: flex;
  align-items: center;
  gap: 10px;
}

/* 选择代码显示区域 */
.selected-code-display {
  background: #f8f9fa;
  border: 2px solid #67c23a;
  border-radius: 8px;
  margin-bottom: 16px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(103, 194, 58, 0.15);
}

.selected-code-header {
  background: #67c23a;
  color: white;
  padding: 8px 16px;
  font-size: 13px;
  font-weight: 600;
  display: flex;
  align-items: center;
  gap: 8px;
}

.selected-code-content {
  padding: 12px 16px;
  max-height: 150px;
  overflow-y: auto;
}

.code-preview {
  margin: 0;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
  line-height: 1.4;
  color: #2c3e50;
  background: transparent;
  white-space: pre-wrap;
  word-break: break-all;
}

/* AI输入框选择状态样式 */
.ai-prompt-input.with-selection >>> .el-textarea__inner {
  border-color: #67c23a;
  box-shadow: 0 0 0 2px rgba(103, 194, 58, 0.2);
}

.ai-prompt-input.with-selection >>> .el-textarea__inner:focus {
  border-color: #67c23a;
  box-shadow: 0 0 0 2px rgba(103, 194, 58, 0.3);
}

.ai-section {
  border-top: 1px solid #e4e7ed;
  background: #f8f9fa;
  padding: 20px;
}

.ai-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 16px;
  gap: 16px;
}

.ai-header-left {
  flex: 1;
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.ai-header-right {
  flex-shrink: 0;
  display: flex;
  align-items: center;
}

.ai-header-right .el-button {
  font-size: 12px;
  border-radius: 16px;
}

.ai-header h5 {
  margin: 0;
  color: #303133;
  font-size: 14px;
  font-weight: 600;
}

.selection-status {
  display: flex;
  align-items: center;
  gap: 10px;
}

.ai-input-area {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.ai-prompt-input {
  background: white;
}

.ai-controls {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
}

.ai-options {
  display: flex;
  gap: 16px;
  flex-wrap: wrap;
}

.ai-buttons {
  display: flex;
  gap: 8px;
  align-items: center;
}

.ai-modify-btn.with-selection {
  animation: pulse-green 2s infinite;
  font-weight: 600;
}

@keyframes pulse-green {
  0% {
    box-shadow: 0 0 0 0 rgba(103, 194, 58, 0.7);
  }
  70% {
    box-shadow: 0 0 0 10px rgba(103, 194, 58, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(103, 194, 58, 0);
  }
}

.ai-progress {
  margin-top: 16px;
  padding: 16px;
  background: white;
  border-radius: 6px;
  border: 1px solid #e4e7ed;
}

.progress-text {
  margin: 8px 0 0 0;
  font-size: 13px;
  color: #606266;
  text-align: center;
}

/* 元素检查模式提示 */
.inspect-mode-tip {
  position: absolute;
  top: 10px;
  left: 50%;
  transform: translateX(-50%);
  z-index: 1000;
  pointer-events: none;
}

.tip-content {
  background: linear-gradient(45deg, #409eff, #36a3f7);
  color: white;
  padding: 8px 16px;
  border-radius: 20px;
  font-size: 13px;
  font-weight: 600;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
  display: flex;
  align-items: center;
  gap: 8px;
  pointer-events: auto;
  animation: tip-bounce 0.5s ease;
}

.tip-content .el-icon-aim {
  font-size: 16px;
}

.tip-content .el-button {
  color: white;
  margin-left: 8px;
}

.tip-content .el-button:hover {
  color: #f0f0f0;
}

@keyframes tip-bounce {
  0% {
    transform: translateX(-50%) translateY(-20px);
    opacity: 0;
  }
  50% {
    transform: translateX(-50%) translateY(5px);
  }
  100% {
    transform: translateX(-50%) translateY(0);
    opacity: 1;
  }
}

/* 检查元素按钮样式 */
.preview-controls .el-button[title*="检查"] {
  position: relative;
}

.preview-controls .el-button[title*="检查"].el-button--primary {
  background: linear-gradient(45deg, #409eff, #36a3f7);
  border: none;
  animation: inspect-active 2s infinite;
}

@keyframes inspect-active {
  0% {
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0.7);
  }
  70% {
    box-shadow: 0 0 0 8px rgba(64, 158, 255, 0);
  }
  100% {
    box-shadow: 0 0 0 0 rgba(64, 158, 255, 0);
  }
}

/* 预览内容在检查模式下的样式 */
.preview-content:has(.inspect-mode-tip) {
  position: relative;
}

/* 响应式设计 */
@media (max-width: 1200px) {
  .main-content {
    flex-direction: column;
  }

  .preview-panel,
  .editor-panel {
    flex: none;
    height: 50vh;
  }

  .viewport-tablet .preview-content iframe,
  .viewport-mobile .preview-content iframe {
    width: 100%;
  }

  .inspect-mode-tip {
    top: 5px;
    left: 10px;
    right: 10px;
    transform: none;
  }

  .tip-content {
    font-size: 12px;
    padding: 6px 12px;
  }

  .ai-header {
    flex-direction: column;
    align-items: stretch;
    gap: 12px;
  }

  .ai-header-left {
    align-items: flex-start;
  }

  .ai-header-right {
    align-self: flex-end;
  }
}

/* 搜索框样式 */
.search-container {
  background: #f8f9fa;
  border-bottom: 1px solid #e4e7ed;
  padding: 12px 20px;
  position: relative;
}

.search-input-group {
  display: flex;
  align-items: center;
  gap: 12px;
}

.search-input {
  flex: 1;
  max-width: 400px;
}

.search-input >>> .el-input-group__prepend {
  background: #409eff;
  color: white;
  border: none;
  padding: 0 12px;
}

.search-input >>> .el-input__inner {
  border-left: none;
  background: white;
}

.search-input >>> .el-input-group__append {
  background: #f5f7fa;
  border-left: none;
  padding: 0 4px;
}

.search-option-btn {
  border: none !important;
  background: transparent !important;
  color: #606266 !important;
  font-size: 12px !important;
  padding: 4px 6px !important;
  margin: 0 1px !important;
  min-width: 28px !important;
  height: 24px !important;
  line-height: 16px !important;
  border-radius: 3px !important;
  font-weight: 600 !important;
}

.search-option-btn:hover {
  background: #e6f7ff !important;
  color: #409eff !important;
}

.search-option-btn.el-button--primary {
  background: #409eff !important;
  color: white !important;
}

.search-option-btn.el-button--primary:hover {
  background: #66b1ff !important;
}

.search-buttons {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-count {
  font-size: 12px;
  color: #606266;
  min-width: 50px;
  text-align: center;
  background: #f0f2f5;
  padding: 4px 8px;
  border-radius: 4px;
  font-weight: 500;
}

.search-count:empty {
  display: none;
}

/* 搜索历史建议 */
.search-suggestions {
  position: absolute;
  top: 100%;
  left: 20px;
  right: 20px;
  background: white;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
  z-index: 1000;
  max-height: 200px;
  overflow-y: auto;
}

.search-suggestions-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 8px 12px;
  background: #f5f7fa;
  border-bottom: 1px solid #e4e7ed;
  font-size: 12px;
  color: #606266;
  font-weight: 500;
}

.search-suggestion-list {
  max-height: 150px;
  overflow-y: auto;
}

.search-suggestion-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 8px 12px;
  cursor: pointer;
  border-bottom: 1px solid #f0f2f5;
  transition: background-color 0.2s;
}

.search-suggestion-item:hover {
  background: #f5f7fa;
}

.search-suggestion-item:last-child {
  border-bottom: none;
}

.search-suggestion-item .el-icon-time {
  color: #c0c4cc;
  font-size: 14px;
}

.suggestion-text {
  flex: 1;
  font-size: 13px;
  color: #303133;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

.suggestion-count {
  font-size: 12px;
  color: #909399;
  background: #f0f2f5;
  padding: 2px 6px;
  border-radius: 3px;
}

/* 搜索状态下的编辑器样式 */
.code-editor-container:has(.search-container) .code-editor {
  border-top: none;
  border-top-left-radius: 0;
  border-top-right-radius: 0;
}

/* 搜索结果高亮样式 */
.code-editor::selection {
  background: #409eff;
  color: white;
}

.code-editor::-moz-selection {
  background: #409eff;
  color: white;
}

/* 滚动条样式 */
.code-editor::-webkit-scrollbar {
  width: 8px;
}

.code-editor::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.code-editor::-webkit-scrollbar-thumb {
  background: #c1c1c1;
  border-radius: 4px;
}

.code-editor::-webkit-scrollbar-thumb:hover {
  background: #a8a8a8;
}
</style>

